/*
 * 新建文件窗口
 */
 DC.front.win.NewFileWin = function(params, config) {
	var fw = this;
	var win_type = 'file',
	    win_title = 'New File Win',
	    field_label = 'File Name',
		blank_text = 'The file name cannot be empty.';
		max_length_text = 'The length of the file name cannot be more than 255.',
		regex_text = 'The file name cannot contain "/\<>*?:"|"';
		
	if (params) {
		win_type = params.type;
		
		if (win_type == 'folder') {
			win_title = 'New Folder Win',
			field_label = 'Folder Name';
			blank_text = 'The folder name cannot be empty.';
			max_length_text = 'The length of the folder name cannot be more than 255.',
			regex_text = 'The folder name cannot contain "/\<>*?:"|"';
		}
	}
	
	var selectedNodePath = Ext.getCmp("explorer_panel").getSelectedNodePath();
	
	var _url = DC.url.CREATE_FILE;
	
	var folder_tree_panel = new DC.front.FolderTreePanel({
		id : 'path_tree_panel'
	});
	
	DC.front.win.NewFileWin.superclass.constructor.call(this, Ext.apply({
    	id : 'new_file_win',
    	title : win_title,
        border : true,
        bodyBorder : true,
        modal : true,
        closeAction : 'close',
        layout : 'fit',
        width : 430,
        height : 500,
        frame : true,
        items : [new Ext.form.FormPanel({
        	region : 'north',
        	header : false,
        	autoWidth : true,
		    autoHeight : true,
		    border : false,
		    bodyStyle : 'padding:10px 10px 0px 10px;',
        	labelAlign : 'top',
        	defaults : {
                labelStyle : 'color:#666666; font-size:12px; text-shadow:1px 0 1px #cccccc;',
                labelSeparator : ''
            },
        	items : [{
        		xtype : 'textfield',
        		id : 'new_file_path_txt',
        		name : 'filePath',
        		width : 395,
        		value : selectedNodePath,
        		fieldLabel : 'Enter or select the parent folder',
	        	allowBlank : false,
	        	blankText : 'The parent folder cannot be empty.',
	        	regex : /^[^\/].*\/$/,
                regexText : 'The parent folder String is Illegal.',
                enableKeyEvents: true, // 只有将此属性设置成true，此控件的键盘事件才生效
                listeners : {
	        		keyup : function() {
	        			var created_btn = Ext.getCmp('new_file_win_created_btn');
	        			if (this.isValid() && Ext.getCmp('new_file_name_txt').isValid()) {
	        				created_btn.enable();
	        			} else {
	        				created_btn.disable();
	        			}
	        		}
	        	}
        	}]
        }), new Ext.Panel({
        	region : 'center',
        	layout : 'fit',
		    width : 415,
	    	height : 325,
		    border : false,
		    bodyStyle : 'padding:0px 10px;',
		    items : [folder_tree_panel]
        }), new Ext.form.FormPanel({
        	region : 'south',
		    border : false,
		    bodyStyle : 'padding:15px 10px 10px 10px;',
        	labelAlign : 'left',
        	labelWidth : 80,
        	defaults : {
                labelStyle : 'color:#666666; font-size:12px; text-shadow:1px 0 1px #cccccc;'
            },
        	items : [{
        		xtype : 'textfield',
        		id : 'new_file_name_txt',
        		name : 'fileName',
        		fieldLabel : field_label,
        		width : 310,
	        	allowBlank : false,
	        	blankText : blank_text,
	        	maxLength : 255,
                maxLengthText : max_length_text,
                regex : /^[^\/\\<>\*\?\:"\|]*[^\/\\<>\*\?\:"\|]$/,
                regexText : regex_text,
                enableKeyEvents: true,
                listeners : {
	        		keyup : function() {
	        			var created_btn = Ext.getCmp('new_file_win_created_btn');
	        			if (this.isValid() && Ext.getCmp('new_file_path_txt').isValid()) {
	        				created_btn.enable();
	        			} else {
	        				created_btn.disable();
	        			}
	        		}
	        	}
        	}]
        })],
        buttons : [{
        	id : 'new_file_win_created_btn',
			text : 'Create',
			disabled : true,
			handler : function(){
				var file_path = Ext.getCmp('new_file_path_txt');
				var file_name = Ext.getCmp('new_file_name_txt');
				var file_path_value = file_path.getValue();
		    	var file_name_value = file_name.getValue();
				if (file_path.isValid() && file_name.isValid()) {
					DC.util.CommonAction.loadMask("Creating...");
					Ext.Ajax.request({
					    url : _url,
					    method : 'POST',
					    params : {
					    	"cfile.parentPath" : file_path_value,
					    	"cfile.fileName" : file_name_value,
					    	"cfile.fileType" : win_type
					    },
					    success : function(response, options){
					    	DC.util.CommonAction.unMask();
						    var res = Ext.util.JSON.decode(response.responseText).returnText;
						    if(res.success){// 判断请求是否成功
						    	fw.close();
							    DC.obj.explorer_treePanel.getRootNode().reload();//重新加载树结点.
							    if (win_type == 'file') {
							    	var i = file_name_value.lastIndexOf('.');
							    	var name = "";
							    	var type = "";
							    	if (i<0) {
							    		name = file_name_value;
							    	} else {
							    		name = file_name_value.substring(0, i);
							    		type = file_name_value.substring(i + 1, file_name_value.length);
							    	}
									var path = file_path_value.substring(0, file_path_value.length - 1);
							    	var code_editor = new DC.front.CodeEditor({
										parentPath : path,
										fileName : name,
										fileType : type,
										code : ''
									});
							    	var tabPanel_id = "";
							    	if (name = "") {
							    		tabPanel_id = path.replace(/\//g, '_') + '_' + type;
							    	} else {
							    		tabPanel_id = path.replace(/\//g, '_') + '_' + name + '_' + type;
							    	}
							    	DC.obj.editor_tabPanel.addTab({
							    		id : tabPanel_id,
							    		panel : code_editor
							    	});
							    }
						    } else {
							    if (res.type == 'WARNING') {
							    	file_path.markInvalid();
							    	file_name.markInvalid();
			                    } else {
			                    	fw.close();
			                    	Ext.example.msg('Prompt', res.msg, 'prompt');
			                    	//DC.util.CommonAction.showMessage('Application Prompt Win', res.msg, Ext.MessageBox.ERROR);
			                    }
						    }
					    },
					    failure : function(response, options){
					    	DC.util.CommonAction.unMask();
					        fw.close();
	                    	Ext.example.msg('Verification Win', response.responseText, 'error');
					    }
				    });
				}
			} 
		}, {
			text : 'Cancle',
			handler :function(){
				fw.close();
			} 
		}]
    }, config ||{}));
    
    folder_tree_panel.getIdPath(selectedNodePath);
};

Ext.extend(DC.front.win.NewFileWin, Ext.Window, {
	
});

/*
 * 文件夹树
 */
DC.front.FolderTreePanel = function(config) {
	var folderTreePanel = this;
	var url = DC.url.GET_FOLDER_TREE;
	
	DC.front.FolderTreePanel.superclass.constructor.call(this, Ext.apply({
		header : false,
		cmargins : '0 0 0 0',
		border : true,
        autoScroll : true,
        rootVisible : false,
		root : new Ext.tree.AsyncTreeNode({
			id : 'path_tree',
			text : 'Folder'
		}),
		loader : new Ext.tree.TreeLoader({
			preloadChildren : false,
			clearOnLoad : false,
			dataUrl : url
		}),
		listeners : {
			beforeload : function(node) {
				   if (node.getDepth() == 0) {
					   folderTreePanel.loader.dataUrl = url;
					   folderTreePanel.loader.baseParams = {
							depth : 0
					    };
	                } else if (node.getDepth() == 1) {
	                	folderTreePanel.loader.dataUrl = url;
	                	folderTreePanel.loader.baseParams = {
							depth : 1,
							parentPath : node.attributes.text
					    };
					}
	            },
            click : function(node, e) {
			    Ext.getCmp('new_file_path_txt').setValue(folderTreePanel.getNodePath(node));
			}
		}
    }, config ||{}));
};

Ext.extend(DC.front.FolderTreePanel, Ext.tree.TreePanel, {
	getNodePath : function(node) { // 取得某个节点的text路径
		var path = "";
		if (node) {
			var array = node.getPath().split('/');
			for (var i = 2, len = array.length; i < len; i++) {
				path += this.getNodeById(array[i]).attributes.text + "/";
			}
		}
		return path;
	},
	
	getIdPath : function(namePath) { // 通过text路径取得某个节点的id路径
		if (namePath) {
			var array = namePath.split('/');
			var idPath = "";
			var curNode = this.getRootNode();
			curNode.eachChild(function(childNode) {
				//console.log(childNode.attributes.text);
			});
			for (var i = 0, len = array.length - 1; i < len; i++) {
				curNode.eachChild(function(childNode) {
					if (childNode.attributes.text == array[i]) {
						idPath = "/" + childNode.attributes.id;
						curNode = childNode;
					}
				});
				if (idPath == null || idPath == "") {
					break;
				}
			}
		}
	}
});